package com.taptech.doufu.ui.view.personalcenter;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Handler;
import android.os.Message;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.View;

import com.taptech.doufu.util.TTLog;
import com.taptech.doufu.bean.cp.CpBean;
import com.taptech.doufu.R;
import com.taptech.doufu.constant.Constant;
import com.taptech.doufu.ui.view.drawcircle.MyRecyclerView;
import com.taptech.doufu.ui.view.drawcircle.RecyclerViewAdapterAsListView;
import com.taptech.doufu.listener.HttpResponseListener;
import com.taptech.doufu.services.CollectService;
import com.taptech.doufu.services.CpService;
import com.taptech.doufu.util.DiaobaoUtil;
import com.taptech.doufu.util.UIUtil;
import com.taptech.doufu.net.httputils.HttpResponseObject;
import com.taptech.doufu.ui.view.WaitDialog;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by lsy on 2015/8/19.
 */
public class TagsCollectListView implements HttpResponseListener
{

    static final public int REMOVE_TAG_COLLECT_DELETE = 1001;
    static final public int REMOVE_TAG_COLLECT_ADD = 1002;
    static final public int REMOVE_TAG_COLLECT_CANCEL = 1003;
    public static final int TYPE_ORDER = 1;
    public static final int TYPE_TAKEIN = 2;
    private int type;
    private Context mContext;
    private View mRootView;

    // UI控件
    MyRecyclerView mListView;
    RecyclerViewAdapterAsListView listViewAdapter;
    WaitDialog mDialog;

    //=== 数据 ===
    List<CpBean> mDataList;
    // 拉取数据的标记点
    private String last = "";
    // 数据类型
    // 是否还有更多内容
    private boolean hasMoreContent;

    public TagsCollectListView(Context context, View rootView)
    {
        this.mContext = context;
        this.mRootView = rootView;
        initData();
        initView();
        mDialog = new WaitDialog(mContext, R.style.updateDialog);
        //mDialog.show();
        switch (type)
        {
            case TYPE_ORDER:
                CollectService.getInstance().loadCollectTagList(this, last, Constant.PAGE_SIZE_20);
                break;
            case TYPE_TAKEIN:
                CollectService.getInstance().loadTakeInTagList(this, last);
                break;
        }

    }

    public TagsCollectListView(Context context, View rootView, int type)
    {
        this.type = type;
        this.mContext = context;
        this.mRootView = rootView;
        initData();
        initView();
        mDialog = new WaitDialog(mContext, R.style.updateDialog);
        //mDialog.show();
        switch (type)
        {
            case TYPE_ORDER:
                CollectService.getInstance().loadCollectTagList(this, last, Constant.PAGE_SIZE_20);
                break;
            case TYPE_TAKEIN:
                CollectService.getInstance().loadTakeInTagList(this, last);
                break;
        }
    }


    private void initData()
    {
        mDataList = new ArrayList<CpBean>();
    }

    private void initView()
    {
        mListView = (MyRecyclerView) mRootView.findViewById(R.id.tag_collect_listview);
        listViewAdapter = new RecyclerViewAdapterAsListView(mContext, mDataList, mHandler);
        listViewAdapter.setType(type);
        //设置布局方式
        RecyclerView.LayoutManager manager = new LinearLayoutManager(mContext);
        mListView.setLayoutManager(manager);
        mListView.setAdapter(listViewAdapter);
        mListView.setLoadMoreEnable(true);
        mListView.setOnScrollToBottomListener(new MyRecyclerView.OnScrollToBottomListener()
        {
            @Override
            public void loadMore()
            {
                loadMoreData();
                TTLog.d("tag", "the listview has been to bottom");
            }
        });
    }

    @Override
    public void handleResponse(int handleType, HttpResponseObject response)
    {
        if (mDialog != null && mDialog.isShowing())
        {
            mDialog.cancel();
        }
        if (response == null)
        {
            UIUtil.toastMessage(mContext, Constant.loadingFail);
            return;
        }
        if (response.getStatus() == Constant.STATUS_SUCCESS)
        {
            JSONObject data = (JSONObject) response.getData();
            switch (handleType)
            {
                case CollectService.HANDLE_TYPE_LOAD_TAG_TAKEIN:
                case CollectService.HANDLE_TYPE_LOAD_TAG_COLLECTS:
                    try
                    {
                        List<CpBean> dataList = DiaobaoUtil.json2list(CpBean.class, data.getJSONArray("tags"));
                        // 如果还有更多内容
                        if (dataList != null && data.has("last") && !data.getString("last").equals(last))
                        {
                            hasMoreContent = true;
                            mDataList.addAll(dataList);
                            //listViewAdapter.notifyItemRangeInserted(mDataList.size() - dataList.size(), dataList.size());
                            listViewAdapter.notifyDataSetChanged();
                        } else
                        {
                            hasMoreContent = false;
                            listViewAdapter.pullComplete(true);
                        }
                        /*// 是否有更多内容
                        if (dataList != null && dataList.size() == Constant.PAGE_SIZE_20){
                            hasMoreContent = true;
                            mDataList.addAll(dataList);
                            listViewAdapter.notifyItemRangeInserted(mDataList.size() - dataList.size(), dataList.size());
                        }else if (dataList != null && dataList.size() < Constant.PAGE_SIZE_20 ){
                            hasMoreContent = false;
                            mDataList.addAll(dataList);
                            listViewAdapter.notifyItemRangeInserted(mDataList.size() - dataList.size(), dataList.size());
                            listViewAdapter.removeFooterView();
                            listViewAdapter.addFooterView(R.layout.no_more_content_footerview);
                        }
                        else {
                            listViewAdapter.removeFooterView();
                            listViewAdapter.addFooterView(R.layout.no_more_content_footerview);
                        }*/
                        // 获得上次拉取的标记
                        last = data.getString("last");
                    } catch (JSONException e)
                    {
                        e.printStackTrace();
                    }
                    break;
            }
        }
    }

    private synchronized void loadMoreData()
    {
        if (hasMoreContent)
        {
            switch (type)
            {
                case TYPE_ORDER:
                    CollectService.getInstance().loadCollectTagList(this, last, Constant.PAGE_SIZE_20);
                    break;
                case TYPE_TAKEIN:
                    CollectService.getInstance().loadTakeInTagList(this, last);
                    break;
            }
            hasMoreContent = false;
        }
    }

    Handler mHandler = new Handler()
    {
        @Override
        public void handleMessage(Message msg)
        {
            super.handleMessage(msg);
            switch (msg.what)
            {
              /*  case TagsCollectListView.REMOVE_TAG_COLLECT_DELETE:
                    ListViewUtil.deleteItemTagCollect(mContext, mDialog, mDataList, listViewAdapter, msg.arg1, msg.obj.toString(), null);
                    break;*/
                case TagsCollectListView.REMOVE_TAG_COLLECT_CANCEL:
                    cancelItemTagOrder(msg.arg1, (CpBean) msg.obj);
                    break;
                case TagsCollectListView.REMOVE_TAG_COLLECT_ADD:
                    addItemTagOrder(msg.arg1, (CpBean) msg.obj);
                    break;
                default:
                    break;
            }
        }
    };


    private void cancelItemTagOrder(final int position, final CpBean cpBean)
    {
        switch (type)
        {
            case TYPE_ORDER:
                new AlertDialog.Builder(mContext).setTitle("确定订阅?").setNegativeButton("取消", null).setPositiveButton("确定", new DialogInterface.OnClickListener()
                {
                    @Override
                    public void onClick(DialogInterface dialog, int which)
                    {

                        cancelItemTagCollectOrder(cpBean, position);
                    }
                }).show();
                break;
            case TYPE_TAKEIN:
                cancelItemTagCollectOrder(cpBean, position);
                break;
        }
    }

    private void cancelItemTagCollectOrder(final CpBean cpBean, final int mDelPosition)
    {
        final HttpResponseListener httpResponseListener = new HttpResponseListener()
        {
            @Override
            public void handleResponse(int handleType, HttpResponseObject response)
            {
                if (mDialog != null && mDialog.isShowing())
                {
                    mDialog.dismiss();
                }
                try
                {
                    if (response.getStatus() == 0)
                    {
                        switch (handleType)
                        {
                            case CollectService.HANDLE_TYPE_REMOVE_TAG_COLLECT:
                                switch (type)
                                {
                                    case TYPE_ORDER:
                                        mDataList.remove(mDelPosition);
                                        listViewAdapter.notifyDataSetChanged();
                                        break;
                                    case TYPE_TAKEIN:
                                        mDataList.get(mDelPosition).setFollowing("0");
                                        listViewAdapter.notifyDataSetChanged();
                                        break;
                                }
                                break;
                            case CpService.HANDLE_TYPE_CANCEL_CP:
                                switch (type)
                                {
                                    case TYPE_ORDER:
                                        mDataList.remove(mDelPosition);
                                        listViewAdapter.notifyDataSetChanged();
                                        break;
                                    case TYPE_TAKEIN:
                                        mDataList.get(mDelPosition).setFollowing("0");
                                        listViewAdapter.notifyDataSetChanged();
                                        break;
                                }
                                break;

                        }
                    } else
                    {
                        if (response.getUser_msg() != null)
                        {
                            UIUtil.toastMessage(mContext, response.getUser_msg());
                        } else
                        {
                            UIUtil.toastMessage(mContext, Constant.loadingFail);
                        }
                    }
                } catch (Exception e)
                {
                }
            }
        };
        switch (Integer.parseInt(cpBean.getType_id()))
        {
            case 18:
                CpService.getInstance().cancelCp(cpBean.getId(), httpResponseListener);
                break;
            default:
                CollectService.getInstance().removeCollectTagRequest(httpResponseListener, cpBean.getName());
                break;
        }
        if (mDialog != null)
        {

            mDialog.show();
        }

    }

    private void addItemTagOrder(final int mDelPosition, final CpBean cpBean)
    {
       /* new AlertDialog.Builder(mContext).setTitle("确定订阅?").setNegativeButton("取消", null).setPositiveButton("确定", new DialogInterface.OnClickListener()
        {
            @Override
            public void onClick(DialogInterface dialog, int which)
            {

                addItemTagCollectOrder(tagString, mDelPosition);
            }
        }).show();*/
        addItemTagCollectOrder(cpBean, mDelPosition);
    }

    private void addItemTagCollectOrder(final CpBean cpBean, final int mDelPosition)
    {
        final HttpResponseListener httpResponseListener = new HttpResponseListener()
        {
            @Override
            public void handleResponse(int handleType, HttpResponseObject response)
            {
                if (mDialog != null && mDialog.isShowing())
                {
                    mDialog.dismiss();
                }
                try
                {
                    if (response.getStatus() == 0)
                    {
                        switch (handleType)
                        {
                            case CpService.HANDLE_TYPE_ADD_CP:
                            case CollectService.HANDLE_TYPE_ADD_TAG_COLLECT:
                                mDataList.get(mDelPosition).setFollowing("1");
                                listViewAdapter.notifyDataSetChanged();
                                break;
                        }
                    } else
                    {
                        if (response.getUser_msg() != null)
                        {
                            UIUtil.toastMessage(mContext, response.getUser_msg());
                        } else
                        {
                            UIUtil.toastMessage(mContext, Constant.loadingFail);
                        }
                    }
                } catch (Exception e)
                {
                }
            }
        };
        switch (Integer.parseInt(cpBean.getType_id()))
        {
            case 18:
                CpService.getInstance().addCp(cpBean.getId(), httpResponseListener);
                break;
            default:
                CollectService.getInstance().addCollectTagRequest(httpResponseListener, cpBean.getName());
                break;
        }
        // 由于话题和小说在收藏内用的同一个type16 但展现数据里小说type18话题是16
        if (mDialog != null)
        {

            mDialog.show();
        }

    }
}
